<template>
  <section class="main-page">
    <div class="map-content">
      <div v-show="!isHideTree && !isFullScreen" class="map-content-left">
        <!-- <i class="el-icon-map-location"></i> -->
        <el-card class="map-area-tree">
          <div slot="header"
              class="clearfix">
            <span>站点信息</span>
          </div>
          <el-input placeholder="输入关键字进行过滤"
                    size="small"
                    v-model="filterText">
          </el-input>
          <el-tree :data="deviceTree"
                  :props="defaultProps"
                  default-expand-all
                  ref="tree"
                  :filter-node-method="filterNode"
                  @node-click="handleNodeClick">
          </el-tree>
        </el-card>
      </div>
      <div class="map-content-right">
        <div class="map-filter">
          <span class="filter-tips">图层：</span>
          <el-checkbox-group class="map-filter-list"
                             v-model="checkList"
                             @change="mapFilter">
            <el-checkbox label="flowFlag">流量站</el-checkbox>
            <el-checkbox label="gateFlag">闸控站</el-checkbox>
            <el-checkbox label="videoFlag">视频站</el-checkbox>
            <el-checkbox label="pipeFlag">管道站</el-checkbox>
            <el-checkbox label="waterGaugeFlag">水尺站</el-checkbox>
          </el-checkbox-group>
        </div>
        <div id="map-container"></div>
        <div class="hide-tree" @click="onHideTree" v-show="!isFullScreen">
          <i :class="isHideTree ? 'el-icon-arrow-right' : 'el-icon-arrow-left' "></i>
        </div>
        <div class="full-screen" @click="onFullScreen">
          <el-switch
            v-model="isFullScreen">
          </el-switch>
        </div>
      </div>
    </div>
    <info-window v-show="isShowInfoWindow"
                 ref="infoWindow"
                 :info-window="infoWindowContainer"
                 :marker-info="markerInfo"
                 @closeInfoWindow="closeInfoWindow"></info-window>
  </section>
</template>
<script>
import AMapLoader from '@amap/amap-jsapi-loader';
import infoWindow from '../Main/InfoWindow'
import InfoWindow from './InfoWindow.vue';
import testpng from '../../assets/mapImg/reservoirIcon.gif';
import { queryDeviceList } from '@/services/common/common';
export default {
  components: { InfoWindow },
  name: 'main-view',
  comments: {
    infoWindow
  },
  data () {
    return {
      deviceTree: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      isShowInfoWindow: false,
      infoWindowContainer: null,
      markerInfo: {},
      filterText: '',
      checkList: ['flowFlag', 'gateFlag', 'videoFlag', 'pipeFlag', 'waterGaugeFlag'],
      allData: [],
      isFullScreen: false,
      isHideTree: false
    }
  },
  created () {

  },
  mounted () {
    // 初始化节点树
    this.initDeviceTree();
  },
  unmounted () {
    this.mapContainer?.destroy();
  },
  methods: {
    initDeviceTree () {
      queryDeviceList({}).then(res => {
        const { data = [] } = res;
        this.deviceTree = [{
          name: '桂花湾罐区',
          children: data
        }];
        this.allData = data;
        // 初始化地图组件
        this.initAMap(data);
      });
    },
    initAMap (data) {
      window._AMapSecurityConfig = {
        securityJsCode: 'd39d9b84003fedf6e5c3e5c1c4c0e3c1',
      };
      AMapLoader.load({
        key: 'f8154836bede178eb9891e26ff42c0b6',
        version: '2.0'
      }).then((AMap) => {
        this.AMap = AMap;
        this.mapContainer = new AMap.Map('map-container', {
          zoom: 15,
          center: [105.0697577, 30.37079791],
          layers: [new AMap.TileLayer.Satellite(), new AMap.TileLayer.RoadNet()],
        });

        AMap.plugin(['AMap.DistrictSearch', 'AMap.Geocoder'], () => {//异步加载插件
          // const geocoder = new AMap.Geocoder({
          //   city: '资阳市' // city 指定进行编码查询的城市，支持传入城市名、adcode 和 citycode
          // });
          // const address = '资阳市乐至县';
          // geocoder.getLocation(address, (status, result) => {
          //   if (status === 'complete' && result.info === 'OK') {
          //     // result中对应详细地理坐标信息
          //     // const center = result.geocodes[0].location
          //     this.mapContainer.setCenter(new AMap.LngLat(105.04925912, 30.38287797));
          //   }
          // })
          const districtSearch = new AMap.DistrictSearch({
            // 关键字对应的行政区级别，country表示国家
            level: 'district',
            extensions: 'all',
            //  显示下级行政区级数，1表示返回下一级行政区
            subdistrict: 3,
            showbiz: false
          });
          // 搜索所有省/直辖市信息
          districtSearch.search('乐至县', (status, result) => {
            // 查询成功时，result即为对应的行政区信息
            const districtList = result.districtList;
            let boundaries = districtList[0] ? districtList[0].boundaries : [];
            // var bounds = result.districtList[0].boundaries;
            if (boundaries) {
              //生成行政区划polygon
              for (var i = 0; i < boundaries.length; i += 1) {//构造MultiPolygon的path
                boundaries[i] = [boundaries[i]]
              }
              this.addPolygon(boundaries, AMap);
            }
          });
        });
        this.addMarker(data || [], AMap);
      }).catch((e) => {
        console.log(e)
      })
    },

    // 绘制边界
    addPolygon (data, AMap) {
      let polygon = new AMap.Polygon({
        path: data,
        strokeColor: '#00ecfc',
        strokeWeight: 2,
        strokeOpacity: 1,
        fillOpacity: 0,
        strokeDasharray: [5, 5],
      });
      polygon.on('mouseover', () => {
        polygon.setOptions({
          strokeWeight: 3,
        })
      })
      polygon.on('mouseout', () => {
        polygon.setOptions({
          strokeWeight: 2,

        })
      })
      this.mapContainer.add(polygon);
    },
    // 标记设备
    addMarker (data = [], AMap) {
      const markerList = [];
      this.infoWindowContainer = new AMap.InfoWindow({
        isCustom: true,  //使用自定义窗体
        content: '',
        offset: new AMap.Pixel(0, -30)
      });
      data.forEach((item) => {
        const markerIcon = new AMap.Icon({
          // 图标尺寸
          size: new AMap.Size(40, 40),
          // 图标的取图地址
          image: testpng,
          // 图标所用图片大小
          imageSize: new AMap.Size(40, 40),
          // 图标取图偏移量
          imageOffset: new AMap.Pixel(-5, 0)
        });
        const markerItem = new AMap.Marker({
          position: new AMap.LngLat(item.longitude, item.latitude),
          icon: markerIcon,
          offset: new AMap.Pixel(-13, -20)
        });
        markerItem.setExtData({
          id: item.id
        });
        markerItem.on('click', () => {
          this.isShowInfoWindow = true;
          this.markerInfo = item;
          this.mapContainer.setCenter(markerItem.getPosition());
          this.infoWindowContainer.setContent(this.$refs.infoWindow.$el);
          this.infoWindowContainer.open(this.mapContainer, markerItem.getPosition());
        });
        markerList.push(markerItem);
      });
      this.markerList = markerList;
      this.mapContainer.add(markerList);
    },
    handleNodeClick (device) {
      this.isShowInfoWindow = true;
      this.markerInfo = device;
      this.infoWindowContainer.setContent(this.$refs.infoWindow.$el);
      this.infoWindowContainer.open(this.mapContainer, new this.AMap.LngLat(device.longitude, device.latitude));
      this.mapContainer.setCenter(new this.AMap.LngLat(device.longitude, device.latitude));
    },
    filterNode (value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },
    mapFilter (checkList) {
      this.mapContainer.remove(this.markerList);
      let filterList = this.allData.filter(() => true);
      if (checkList.length) {
        filterList = (this.allData || []).filter(item => {
          let flag = false;
          checkList.forEach(child => {
            if (item[child] > 0) {
              flag = true;
              return;
            }
          });
          return flag;
        });
        if (checkList.length === 5) {
          this.addMarker(this.allData || [], this.AMap);
          return
        }
        this.addMarker(filterList || [], this.AMap);
      }
    },
    // 关闭信息窗体回调
    closeInfoWindow () {
      this.isShowInfoWindow = false;
      this.markerInfo = {};
    },
    onHideTree() {
      this.isHideTree = !this.isHideTree;
    },
    onFullScreen() {

    }
  },
  watch: {
    filterText (val) {
      this.$refs.tree.filter(val);
    },
    isFullScreen (val) {
      const headerDom = document.querySelector('.page-header');
      const headerContentDom = document.querySelector('.header-content');
      const pageContentDom = document.querySelector('.page-content');
      headerDom.style.height = '70px';
      headerContentDom.style.display = 'block';
      pageContentDom.style.height = 'calc(100% - 70px)';

      if(val) {
        const headerDom = document.querySelector('.page-header');
        headerDom.style.height = '0px';
        headerContentDom.style.display = 'none';
        pageContentDom.style.height = '100%';
      }
    }
  },
}
</script>

<style lang="scss">
.main-page {
  height: 100%;
  .map-content {
    width: 100%;
    height: 100%;
    padding: 10px;
    box-sizing: border-box;
    display: flex;
    .map-content-left {
      height: 100%;
      .map-area-tree {
        height: 100%;
        overflow-y: auto;
      }
    }
    .map-content-right {
      width: 100%;
      height: 100%;
      background: #fff;
      border-radius: 4px;
      position: relative;
      display: flex;
      flex-direction: column;
      .map-filter {
        width: 100%;
        display: flex;
        align-items: center;
        padding: 15px;
        .filter-tips {
          font-size: 13px;
        }
        .map-filter-list {
          text-align: left;
        }
      }
      #map-container {
        width: 100%;
        border-radius: 4px;
        height: 100%;
      }
      .hide-tree {
        position: absolute;
        top: 48%;
        width: 9px;
        height: 50px;
        border-radius: 0 15px 15px 0;
        background: #fff;
        border: 1px solid #dee5e7;
        border-left: none;
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;
        transition: all 0.3s;
      }
      .full-screen {
        position: absolute;
        top: 15px;
        right: 15px;
      }
    }
    
  }
}
</style>